import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

class NativePage extends StatefulWidget {
  const NativePage({super.key});

  @override
  State<StatefulWidget> createState() => _NativePage();
}

class _NativePage extends State<StatefulWidget> {
  String receiveStr = '';

  String eveanStr = '';

  String basicStr = '';

  static var eventChannel = const EventChannel("EventChannel");
  static var basicChannel =
      const BasicMessageChannel("BasicMessageChannel", StandardMessageCodec());

  @override
  void initState() {
    super.initState();
    const platform = MethodChannel('OtoF');
    platform.setMethodCallHandler((call) {
      String method = call.method;
      Map arg = call.arguments;
      setState(() {
        receiveStr = "从原生接Method: $method, 获取的参数$arg";
      });
      return Future(() => null);
    });

    basicChannel.setMessageHandler((message) async {
      setState(() {
        basicStr = "双向通迅收到从原生事件: $message";
      });
    });

    eventChannel.receiveBroadcastStream().listen((event) {
      String eventStr = event.toString();
      print("event $eventStr");

      setState(() {
        eveanStr = "从原生事件: $eventStr";
      });
    }, onDone: () {
      print("done");
    }, onError: (object) {
      print("on error $object");
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  void sendMsg() async {
    const platform = MethodChannel('FtoO');
    try {
      final data = await platform.invokeMethod("sendO", {"data": "发给原生的消息"});

      setState(() {
        receiveStr = "接收回调的消息: $data";
      });
    } on PlatformException catch (e) {
      setState(() {
        receiveStr = "获取失败: '${e.message}'.";
      });
    }
  }

  void sendBasicMsg() async {
    try {
      final data = await basicChannel.send({"data": "发给原生的消息"});

      setState(() {
        basicStr = "双向通道接收回调的消息: $data";
      });
    } on PlatformException catch (e) {
      setState(() {
        receiveStr = "获取失败: '${e.message}'.";
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text('原生通信'),
      ),
      body: Center(
        child: Column(children: [
          Text(receiveStr),
          FilledButton(
            onPressed: () {
              // 处理按钮点击事件
              sendMsg();
            },
            child: Text('发送信息'),
          ),
          Text(basicStr),
          FilledButton(
            onPressed: () {
              // 处理按钮点击事件
              sendBasicMsg();
            },
            child: Text('双向通迅发送信息'),
          ),
          Text(eveanStr)
        ]),
      ),
    );
  }
}
